package com.epam.qanda.web.servlet.authentication;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.UserService;
import com.epam.qanda.hash.MD5;
import com.epam.qanda.mail.EmailUtility;

public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger("stdout");

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("preg").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StringBuilder message = new StringBuilder();
		message.append("http://");
		message.append(request.getServerName() + ":");
		message.append(request.getServerPort());
		message.append(request.getContextPath());

		User user = new User();
		user.setLogin(request.getParameter("inputLogin"));
		user.setPassword(MD5.getHash(request.getParameter("inputPassword")));
		user.setEmail(request.getParameter("inputEmail"));
		user.setfName(request.getParameter("inputFName"));
		user.setlName(request.getParameter("inputLName"));
		user.setRoleId(3);
		UserService userService = new UserService();
		try {
			userService.create(user);
		} catch (RuntimeException e) {
			request.setAttribute("result", "exist");
			request.getRequestDispatcher("preg").forward(request, response);
			return;
		}
		message.append("/confirmAccount?hash="
				+ ((User) userService.getUserByLogin(user.getLogin())).getHash());
		try {
			new EmailUtility()
					.sendEmail("Confirm account", "Confirm your account " + "<a href='"+message+"'>CONFIRM</a>", user);
		} catch (MessagingException e) {
			LOG.warn(e.getMessage());
		}
		request.setAttribute("result", "registered");
		request.getRequestDispatcher("preg").forward(request, response);
	}
}
